/*
 * Copyright (c) 2009 Frederic Daoud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.stripesbook.rayures.view.velocity;

import java.io.InputStream;
import java.io.Writer;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.stripesbook.rayures.service.TemplateEngine;

/** TODO: cache templates in production mode */
public class VelocityTemplateEngine implements TemplateEngine {
  public static final String DEFAULT_PROPERTIES =
    "/org/stripesbook/rayures/view/velocity/velocity.properties";

  public static final String USER_PROPERTIES = "/velocity.properties";

  public VelocityTemplateEngine() {
    try {
      Properties properties = new Properties();
      properties.putAll(getDefaultProperties());
      properties.putAll(getUserProperties());
      Velocity.init(properties);
    }
    catch (Exception exc) {
      throw new RuntimeException("Could not initialize Velocity properties", exc);
    }
  }

  protected Properties getDefaultProperties() throws Exception {
    Properties properties = new Properties();
    properties.load(getClass().getResourceAsStream(DEFAULT_PROPERTIES));
    return properties;
  }

  protected Properties getUserProperties() throws Exception {
    Properties properties = new Properties();
    InputStream inputStream = getClass().getResourceAsStream(USER_PROPERTIES);
    if (inputStream != null) {
      properties.load(inputStream);
    }
    return properties;
  }

  public String getTemplateFileExtension() {
    return "vm";
  }

  public boolean isTemplateFileNameValid(String fileName) {
    return Velocity.resourceExists(fileName);
  }

  public void write(String templateFileName, Map<String, Object> dataModel, Writer writer)
    throws Exception
  {
    VelocityContext velocityContext = createVelocityContext(dataModel);
    Template template = Velocity.getTemplate(templateFileName);
    template.merge(velocityContext, writer);
  }

  protected VelocityContext createVelocityContext(Map<String, Object> dataModel) {
    VelocityContext velocityContext = new VelocityContext();

    for (Entry<String, Object> entry : dataModel.entrySet()) {
      velocityContext.put(entry.getKey(), entry.getValue());
    }
    return velocityContext;
  }
}
